<template>
  <div v-if="quizData">
    <div class="quiz-container mc">
      <div class="mt-30 mb-20">题目数量：{{ quizData.surveyCount }}</div>
      <div class="content mb-10" v-for="(com, index) in quizData.coms" :key="index">
        <component
          :is="com.type"
          :status="com.status"
          :serialNum="serialNum[index]"
          @updateAnswer="updateAnswer(index, $event)"
        />
      </div>
      <div class="mt-20 mb-20 text-center">
        <el-button type="primary" @click="submitAnswers">提交答案</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { useDark } from '@vueuse/core';
import { ElMessage } from 'element-plus';
import { restoreComponentStatus } from '@/utils';
import { useSurveyNo } from '@/utils/hooks';
import type { Status } from '@/types';
const route = useRoute();
const serialNum = computed(() => useSurveyNo(quizData.value?.coms).value);
type QuizData = {
  coms: Status[];
  surveyCount: number;
};
const quizData = ref<QuizData>({
  coms: [],
  surveyCount: 0,
});
// 用于存储所有问题的答案
const answers = ref<{ [key: number]: string | string[] | number | Date }>({});

onMounted(async () => {
  useDark();
  const quizId = route.params.id;
  // 从服务器获取问卷内容
  const response = await fetch(`/api/getQuiz/${quizId}`);
  const data = await response.json();
  data.coms = JSON.parse(data.coms);
  restoreComponentStatus(data.coms);
  quizData.value = data;
});

function updateAnswer(index: number, answer: string | string[] | number | Date) {
  // index是题目本来的索引，通过serialNum.value[index]获取显示的题目索引
  // 检查 serialNum.value[index] 是否为 null
  const serial = serialNum.value[index];
  if (serial && serial !== null) {
    answers.value[serial] = answer;
  } else {
    // 处理 serialNum.value[index] 为 null 的情况
    console.error(`The serial number at index ${index} is null.`);
  }
}
async function submitAnswers() {
  const quizId = route.params.id;
  await fetch('/api/submitAnswers', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ quizId, answers: answers.value }),
  });
  ElMessage({
    message: '提交成功',
    type: 'success',
  });
}
</script>

<style scoped lang="scss">
.quiz-container {
  width: 800px;
}
</style>
